﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.Office.Interop.Word;
using System.Data;
using System.Windows.Forms;
using ESRI.ArcGIS.Geodatabase;
    
    
namespace ArcMap_AddIn_Tools
{
    public class ExportLayerToWord : ESRI.ArcGIS.Desktop.AddIns.Button
    {
        private Dictionary<IFeatureClass, string> dicLayerInfo = new Dictionary<IFeatureClass, string>();
        private List<DataTable> dataTableList = new List<DataTable>();
        System.Object Nothing = System.Reflection.Missing.Value;
        string statusBarInfo = "";

        public ExportLayerToWord()
        {
        }

        protected override void OnClick()
        {
            try
            {
                statusBarInfo = "开始";
                ArcMap.Application.StatusBar.set_Message(0, statusBarInfo);
                CreateWordFile();
                ArcMap.Application.StatusBar.set_Message(0, statusBarInfo);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected override void OnUpdate()
        {
        }

        private string GetFilePath()
        {
            string inWordPath = "";
            FolderBrowserDialog outputDialog = new FolderBrowserDialog();
            if (outputDialog.ShowDialog() == DialogResult.OK)
            {
                inWordPath = outputDialog.SelectedPath;
                return inWordPath;
            }
            return inWordPath;
        }

        protected string GetDiffTime(DateTime beginTime, DateTime endTime)
        {
            string strResout = "{0}{1}";
            //获得2时间的时间间隔秒计算  
            TimeSpan span = endTime - beginTime;
            int iTatol = Convert.ToInt32(span.TotalSeconds);

            int iMinutes = 1 * 60;
            int iHours = iMinutes * 60;
            int iDay = iHours * 24;
            int iMonth = iDay * 30;
            int iYear = iMonth * 12;

            if (iTatol > iYear)
            {
                return string.Format(strResout, iTatol / iYear, "年");
            }
            else if (iTatol > iMonth)
            {
                return string.Format(strResout, iTatol / iMonth, "月");
            }
            else if (iTatol > iDay)
            {
                return string.Format(strResout, iTatol / iDay, "天");
            }
            else if (iTatol > iHours)
            {
                return string.Format(strResout, iTatol / iHours, "小时");
            }
            else if (iTatol > iMinutes)
            {
                return string.Format(strResout, iTatol / iMinutes, "分钟");
            }
            else
            {
                return string.Format(strResout, iTatol, "秒");
            }

        }

        public void CreateWordFile()
        {
            //创建Word文档
            Microsoft.Office.Interop.Word.Application WordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);
            try
            {
                object filename = GetFilePath();
                filename = filename + "\\" + "图层结构.doc";
                if (File.Exists((string)filename))
                {
                    MessageBox.Show("该文件已经存在，请选择其他位置或者删除已有文件！");
                    return;
                }

                FeatureClassInfo featureClassInfo = new FeatureClassInfo();
                dataTableList = featureClassInfo.GetFeatureClassStruct();
                if (dataTableList == null) return;
                dicLayerInfo = featureClassInfo.DicLayerInfo;

                for (int i = 0; i < dataTableList.Count; i++)
                {
                    DataTable DataTable = dataTableList[i];
                    LoadWordFile2(DataTable, WordApp, WordDoc, dicLayerInfo);
                    LoadWordFile(DataTable, WordApp, WordDoc, dicLayerInfo);
                    statusBarInfo = string.Format("进度:{0}/{1};图层名：{2}.", i + 1, dataTableList.Count, DataTable.TableName);
                    ArcMap.Application.StatusBar.set_Message(0, statusBarInfo);
                }

                //文件保存
                WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                //避免弹出normal.dotm被使用的对话框,自动保存模板  
                WordApp.NormalTemplate.Saved = true;
                //先关闭打开的文档（注意saveChanges选项）  
                System.Object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;
                System.Object originalFormat = Type.Missing;
                System.Object routeDocument = Type.Missing;
                WordApp.Documents.Close(ref saveChanges, ref originalFormat, ref routeDocument);

                //若已经没有文档存在，则关闭应用程序  
                if (WordApp.Documents.Count == 0)
                {
                    WordApp.Application.Quit(ref Nothing, ref Nothing, ref Nothing);
                }
                //WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                //WordApp.Application.Quit(ref Nothing, ref Nothing, ref Nothing);
                //WordDoc = null;
                //WordApp = null;
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);

            }
        }

        public void LoadWordFile2(DataTable DataTable, Microsoft.Office.Interop.Word.Application WordApp, Document WordDoc, Dictionary<IFeatureClass, string> DicLayerInfo)
        {
            try
            {
                int rows = DataTable.Rows.Count;
                int columns = DataTable.Columns.Count;

                // 计算Word文档页数
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int n = WordDoc.ComputeStatistics(stat, ref  Nothing);

                //  跳转到指定页
                object What = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
                object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
                object Name = (object)n; // 页数
                WordDoc.ActiveWindow.Selection.GoTo(ref What, ref Which, ref Nothing, ref Name); // 第二个参数可以用Nothing
                WordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString();

                string titleName = "";
                foreach (KeyValuePair<IFeatureClass, string> item in dicLayerInfo)
                {
                    IFeatureClass featureClass = item.Key;
                    IDataset dataSet = featureClass as IDataset;
                    if (dataSet.Name == DataTable.TableName)
                    {
                        titleName = item.Value;
                    }
                }
                WordDoc.Paragraphs.Last.Range.Text = titleName + "\r\n" +
                                                     "【表名】：" + DataTable.TableName + "\r\n" +
                                                     "【中文名】：" + titleName + "\r\n" +
                                                     "【描述】：" + "\r\n";//“落款”
            }
            catch (Exception ex)
            { throw ex; }
        }

        public void LoadWordFile(DataTable DataTable, Microsoft.Office.Interop.Word.Application WordApp, Document WordDoc, Dictionary<IFeatureClass, string> DicLayerInfo)
        {
            try
            {
                int rows = DataTable.Rows.Count;
                int columns = DataTable.Columns.Count;

                // 计算Word文档页数
                Microsoft.Office.Interop.Word.WdStatistic stat = Microsoft.Office.Interop.Word.WdStatistic.wdStatisticPages;
                int n = WordDoc.ComputeStatistics(stat, ref  Nothing);

                //  跳转到指定页
                object What = Microsoft.Office.Interop.Word.WdGoToItem.wdGoToPage;
                object Which = Microsoft.Office.Interop.Word.WdGoToDirection.wdGoToNext;
                object Name = (object)n; // 页数
                WordDoc.ActiveWindow.Selection.GoTo(ref What, ref Which, ref Nothing, ref Name); // 第二个参数可以用Nothing
                WordDoc.ActiveWindow.Selection.Paragraphs[1].Range.Text.ToString();

                //移动焦点并换行
                //object count = num;
                object count = 300;
                object WdLine = Microsoft.Office.Interop.Word.WdUnits.wdLine;//换一行;
                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
                WordApp.Selection.MoveEnd(ref WdLine, ref count);
                WordApp.Selection.TypeParagraph();//插入段落

                string titleName = "";
                foreach (KeyValuePair<IFeatureClass, string> item in dicLayerInfo)
                {
                    IFeatureClass featureClass = item.Key;
                    IDataset dataSet = featureClass as IDataset;
                    if (dataSet.Name == DataTable.TableName)
                    {
                        titleName = item.Value;
                    }
                }

                //文档中创建表格
                Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordDoc.Paragraphs.Last.Range, rows + 3, 7, ref Nothing, ref Nothing);
                ////文档中创建表格
                //Microsoft.Office.Interop.Word.Table newTable = WordDoc.Tables.Add(WordDoc.Paragraphs.Last.Range, rows + 2, 7, ref Nothing, ref Nothing);
                //设置表格样式
                //newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                newTable.Borders.OutsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;
                newTable.Borders.InsideLineStyle = Microsoft.Office.Interop.Word.WdLineStyle.wdLineStyleSingle;

                //设置列的宽度
                newTable.Columns[1].Width = 40f;
                newTable.Columns[2].Width = 90f;
                newTable.Columns[3].Width = 90f;
                newTable.Columns[4].Width = 55f;
                newTable.Columns[5].Width = 40f;
                newTable.Columns[6].Width = 40f;
                newTable.Columns[7].Width = 50f;

                //填充表格内容  第一行
                newTable.Cell(1, 1).Range.Text = titleName;
                newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
                //合并单元格
                newTable.Cell(1, 1).Merge(newTable.Cell(1, 7));
                //第一行颜色
                //newTable.Cell(1, 1).Range.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray20;
                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                //填充表格内容  第二行
                newTable.Cell(2, 1).Range.Text = DataTable.TableName;
                newTable.Cell(2, 1).Range.Bold = 2;//设置单元格中字体为粗体
                //合并单元格
                newTable.Cell(2, 1).Merge(newTable.Cell(2, 7));
                //第二行颜色
                //newTable.Cell(2, 1).Range.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray20;
                newTable.Cell(2, 1).Select();//选中一行
                WordApp.Selection.Cells.VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                WordApp.Selection.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中




                newTable.Cell(3, 1).Range.Text = "序号";
                newTable.Cell(3, 2).Range.Text = "字段名";
                newTable.Cell(3, 3).Range.Text = "描述";
                newTable.Cell(3, 4).Range.Text = "类型";
                newTable.Cell(3, 5).Range.Text = "长度";
                newTable.Cell(3, 6).Range.Text = "可空";
                newTable.Cell(3, 7).Range.Text = "默认值";

                for (int i = 0; i < 7; i++)
                {
                    newTable.Cell(3, i + 1).Range.Bold = 2;
                    newTable.Cell(3, i + 1).Range.Shading.ForegroundPatternColor = Microsoft.Office.Interop.Word.WdColor.wdColorGray20;
                }

                //newTable.Cell(3, 1).Range.Bold = 2;
                //newTable.Cell(3, 2).Range.Bold = 2;
                //newTable.Cell(3, 3).Range.Bold = 2;
                //newTable.Cell(3, 4).Range.Bold = 2;
                //newTable.Cell(3, 5).Range.Bold = 2;
                //newTable.Cell(3, 6).Range.Bold = 2;
                //newTable.Cell(3, 7).Range.Bold = 2;

                //newTable.Cell(3, 1).VerticalAlignment = Microsoft.Office.Interop.Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中

                for (int i = 0; i < rows; i++)
                {
                    for (int j = 0; j < columns; j++)
                    {
                        newTable.Cell(i + 4, j + 1).Range.Text = DataTable.Rows[i][j].ToString();
                    }
                }

                newTable.Select();//选中表格
                WordDoc.ActiveWindow.Selection.Tables[1].Rows.Alignment = WdRowAlignment.wdAlignRowCenter;//表格居中
            }
            catch (Exception ex)
            { throw ex; }
        }

    }
}
